package com.tedu.food.sys.service.impl;

import com.tedu.food.common.config.PageProperties;
import com.tedu.food.common.exception.ServiceException;
import com.tedu.food.common.util.RedisUtils;
import com.tedu.food.common.util.ShiroUtils;
import com.tedu.food.common.util.UUIDUtils;
import com.tedu.food.common.vo.OrderMasterVo;
import com.tedu.food.common.vo.OrderVo;
import com.tedu.food.common.vo.PageObject;
import com.tedu.food.sys.dao.CartItemDao;
import com.tedu.food.sys.dao.OrderItemDao;
import com.tedu.food.sys.dao.OrderMasterDao;
import com.tedu.food.sys.entity.CartItem;
import com.tedu.food.sys.entity.Member;
import com.tedu.food.sys.entity.OrderItem;
import com.tedu.food.sys.entity.OrderMaster;
import com.tedu.food.sys.service.OrderMasterService;

import lombok.Data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 
 * @author 作者:tiankun
 * @createdTime 创建时间 :2019年11月22日 上午11:26:03
 *
 */

@Service
@Data
public class OrderMasterServiceImpl implements OrderMasterService {

	@Autowired
	private OrderMasterDao orderMasterDao;
	@Autowired

	private OrderItemDao orderItemDao;
	@Autowired
	private CartItemDao cartItemDao;
	private AtomicInteger at = new AtomicInteger(1);

	@Autowired
	private PageProperties pageProperties;

	@Override
	public List<OrderMaster> findAllPaidOrders() {
		List<OrderMaster> allPaidOrders = orderMasterDao.findAllPaidOrders();
		return allPaidOrders;
	}

	@Override
	public List<OrderMaster> findAllCompletedOrders() {
		List<OrderMaster> allCompletedOrders = orderMasterDao.findAllCompletedOrders();
		return allCompletedOrders;
	}

	/**
	 * 根据订单id查找具体订单
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public OrderVo findOrderMasterByOrderId(Integer id) {
		if (id == null || id < 0)
			throw new IllegalArgumentException("参数订单id无效");
		OrderVo orderVo = orderMasterDao.findOrderMasterByOrderId(id);
		if (orderVo == null)
			throw new ServiceException("该订单可能不存在");
		return orderVo;
	}

	/**
	 * ] 根据订单状态查询用户订单信息 不传状态,状态为null,代表查询用户所有订单
	 * 
	 * @param orderStatus
	 * @return
	 */
	@Override
	public List<OrderMasterVo> findOrderMastersByStatus(Integer orderStatus) {
		// 用户id从session拿(登录存用户信息到session
		Member user = ShiroUtils.getUser();
		List<OrderMasterVo> orderVoList = orderMasterDao.findOrderMastersByStatus(user.getId(), orderStatus);
		return orderVoList;
	}

	/**
	 * 用户下单操作 包括支付和待支付
	 * 
	 * @param entity
	 * @param goodsIds
	 * @return
	 */
	@Override
	public Integer insertOrderMaster(OrderMaster entity, Integer[] goodsIds) {
		Member user = ShiroUtils.getUser();
		// 1.校验参数
		// 2.根据goodsIds查购物车的数据
		List<CartItem> cartItemList = cartItemDao.findCartItemsByGoodsIds(goodsIds, user.getId());
		// 3.判断购物车数据
		if (cartItemList == null || cartItemList.size() == 0)
			throw new ServiceException();
		for (CartItem cartItem : cartItemList) {
			if (cartItem.getStatus() == 0)
				throw new ServiceException(cartItem.getGoodsName() + "刚售罄,请重新下单");
		}
		String orderNo = UUIDUtils.getOrderIdByTime();// 订单编号
		entity.setUserId(user.getId()); // 从session中获取
		entity.setOrderNo(orderNo);
		String orderGetNo = null; // 取餐号
		// 4.判断是否支付,支付生成唯一取餐号
		if (entity.getOrderStatus() == 1) {
			int i = at.getAndIncrement();
			if (i >= 10)
				orderGetNo = "0" + i;
			else
				orderGetNo = "00" + i;
			entity.setOrderGetNo(orderGetNo);
			entity.setOrderPayTime(new Date());
			orderNo = UUIDUtils.getOrderIdByTime() + orderGetNo;
            entity.setOrderNo(orderNo);
        }
		// 5.插入订单
		Integer orderMasterRows = orderMasterDao.insertOrderMaster(entity);
		// 6.插入订单项
		List<OrderItem> orderItemList = new ArrayList<>();
		for (CartItem cartItem : cartItemList) {
			OrderItem orderItem = new OrderItem();
			orderItem.setOrderId(entity.getId());
			orderItem.setGoodsId(cartItem.getGoodsId());
			orderItem.setGoodsName(cartItem.getGoodsName());
			orderItem.setGoodsLogo(cartItem.getGoodsLogo());
			orderItem.setNumber(cartItem.getNumber());
			orderItem.setPrice(cartItem.getPrice());
			orderItemList.add(orderItem);
		}
		Integer orderItemRows = orderItemDao.insertOrderItems(orderItemList);
		// 7.购物车数据删除
		cartItemDao.deleteCartItemsByGoodsIds(goodsIds, user.getId());
		// 5.未支付,为该订单设置定时删除任务
		if (entity.getOrderStatus() == 0) {
			RedisUtils.set("orderId"+entity.getId(), "orderId"+entity.getId(), 1);
		}
		return orderMasterRows;
	}

	/**
	 * 用户提交待支付的订单
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public Integer updateOrderMasterStatus(Integer id) {
		if (id == null || id <= 0)
			throw new IllegalArgumentException("参数无效");
		int i = at.getAndIncrement();
		String orderGetNo = null;
		if (i >= 10)
			orderGetNo = "0" + i;
		else
			orderGetNo = "00" + i;
        String orderNo = UUIDUtils.getOrderIdByTime() + orderGetNo;
		Integer rows = orderMasterDao.updateOrderMasterStatus(id, orderGetNo, orderNo);
		if (rows == 0) {
			at.set(i - 1); // 表示此订单无效,取餐号应该回到原来的值
			throw new ServiceException("该订单无效,请重新下单");
		}
		return rows;
	}

	/**
	 * 给商家看的订单信息
	 */
	@Override
	public PageObject<OrderMaster> findPageOrders(String orderType, Integer pageCurrent) {
		// 验证参数的合法性
		if (pageCurrent == null || pageCurrent < 1)
			throw new IllegalArgumentException("当前页码不正确");
		// 基于条件查询总记录数
		Integer orderStatus = -1;
		if ("已支付订单".equals(orderType)) {
			orderStatus = 1;
		} else if ("已完成订单".equals(orderType)) {
			orderStatus = 2;
		}
		int rowCount = 0;
		// 定义pageSize
		Integer pageSize = pageProperties.getPageSize();
		// 计算startIndex
		Integer startIndex = (pageCurrent - 1) * pageSize;
		// 查询当前页信息
		List<OrderMaster> records = orderMasterDao.findPageOrders(startIndex, pageSize, orderStatus);
		rowCount = orderMasterDao.getRowCount(orderStatus);
		if ("全部订单".equals(orderType)) {
			rowCount = orderMasterDao.getRowCount(1, 2);
			records = orderMasterDao.findPageOrders(startIndex, pageSize, 1, 2);
		}
		// 验证记录
		if (rowCount == 0)
			throw new ServiceException("系统没有查到对应记录");
		// 返回封装的分页信息
		return new PageObject<>(pageCurrent, pageSize, rowCount, records);
	}

	@Override
	public int updateOrderStatusById(Integer id) {
		int rows = orderMasterDao.updateOrderStatusById(id);
		return rows;
	}
	/** 用户取消订单 */
	@Override
	public Integer cancleOrderMaster(Integer id) {
		if(id == null || id <= 0)
			throw new IllegalArgumentException("参数无效");
		int rows = orderMasterDao.deleteOrderMasterById(id);
		//表示该未支付订单超时自动删除了,(顾客待在待支付订单页面过长,再取消)
		if(rows == 0)
			throw new ServiceException("该订单已超时删除");
		//删除订单对应的订单项
		orderItemDao.deleteOrderItemsByOrderId(id);
		return rows;
	}


}
